package com.tianhui.consignortwofei.mvp.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

import androidx.annotation.NonNull;

import com.fgs.common.CommonFragment;
import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.adapter.FragmentPagerAdapter;
import com.fgs.common.appStatus.AppStatusConstant;
import com.fgs.common.interf.OnDialogClickListener;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.DateUtil;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.widget.CustomViewPager;
import com.fgs.common.widget.PermissionDialog;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.bugly.HotUpdateController;
import com.tianhui.consignortwofei.constant.PlatformConfig;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.model.DriverModel;
import com.tianhui.consignortwofei.mvp.model.FuJianListBean;
import com.tianhui.consignortwofei.mvp.model.MessageModel;
import com.tianhui.consignortwofei.mvp.model.UserInfoModel;
import com.tianhui.consignortwofei.mvp.model.enty.ApiModel;
import com.tianhui.consignortwofei.mvp.model.enty.GoodsInfo;
import com.tianhui.consignortwofei.mvp.model.enty.HandleMqttBean;
import com.tianhui.consignortwofei.mvp.model.enty.UserInfo;
import com.tianhui.consignortwofei.mvp.model.enty.XiaoShouHttpBean;
import com.tianhui.consignortwofei.mvp.model.enty.message.MessageQualityInfo;
import com.tianhui.consignortwofei.mvp.model.hetong.HuiKuanListBean;
import com.tianhui.consignortwofei.mvp.ui.activity.fujian.UnHuiKuanListActivity;
import com.tianhui.consignortwofei.mvp.ui.fragment.HomeFragment;
import com.tianhui.consignortwofei.mvp.ui.fragment.MessageFragment;
import com.tianhui.consignortwofei.mvp.ui.fragment.MineFragment;
import com.tianhui.consignortwofei.mvp.ui.fragment.WaybillFragment;

import com.tianhui.consignortwofei.other.EventWhat;
import com.tianhui.consignortwofei.role.RoleController;
import com.tianhui.consignortwofei.update.ConsignorCheckUpdate;
import com.tianhui.consignortwofei.utils.NotificationsUtils;
import com.tianhui.consignortwofei.utils.Util;
import com.tianhui.consignortwofei.widget.ChartBarView;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;


public class MainActivity extends BaseActivity {

    @BindView(R.id.activity_main_viewPager)
    CustomViewPager mViewPager;
    @BindView(R.id.activity_main_slidingTabLayout)
    SlidingTabLayout mTabLayout;
    private List<CommonFragment> mFragmentList = new ArrayList<>();
    private FragmentPagerAdapter mPagerAdapter;
    private MessageModel mMessageModel;
    private UserInfoModel mUserInfoModel;
    private DriverModel driverModel;

    @Override
    public String getToolbarTitle() {
        return "一键发货";
    }

    @Override
    public boolean isShowToolbar() {
        return false;
    }

    @Override
    public boolean isShowBackIcon() {
        return false;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    }

    @Override
    public void init() {

        mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager());
        mPagerAdapter.setFragments(createFragmentList());
        mViewPager.setCanScroll(false);
        mViewPager.setHasEffect(false);
        mViewPager.setOffscreenPageLimit(mFragmentList.size());
        mViewPager.setAdapter(mPagerAdapter);

        initListener();
        mPagerAdapter.setTabTitles(Arrays.asList(getResources().getStringArray(R.array.array_home_tab)));
        mTabLayout.setViewPager(mViewPager);


        mMessageModel = new MessageModel();
        requestMessageQuality(false);

        mUserInfoModel = new UserInfoModel();
        //微信初始化
//        registerWeChat();


        //调用此接口，用于后台记录版本信息
        requestCheckUpdate();

//        getShengShi(false);

//        int rolePosition = SharedPreferenceManager.getInstance().getRolePosition();

//        if (2== rolePosition){
//        //2 销售，3物流
//
//        }else {
            requestUserInfo();
//        }

        try {
            //通知推送
//            String old=(System.currentTimeMillis()-86400000)+"";//昨天时间
//            SharedPreferenceManager.getInstance().setTongZhiFirst(old);
            String tongZhiFirst = SharedPreferenceManager.getInstance().getTongZhiFirst();
            String nowTime = DateUtil.getTime();
            if (TextUtils.isEmpty(tongZhiFirst)){
                SharedPreferenceManager.getInstance().setTongZhiFirst(nowTime);
                getNotification();
            }else {
                Long integer = Long.valueOf(tongZhiFirst);
                if (!DateUtil.isToday(integer)){
                    SharedPreferenceManager.getInstance().setTongZhiFirst(nowTime);
                    getNotification();
                }

            }
        }catch (Exception e){
            SharedPreferenceManager.getInstance().setTongZhiFirst("");
            LogUtil.print(e.toString());
        }



//        inintView();
//        initTuiSong();
        searchHuiKuan();

        ChartBarView.getDressBaesInfo(this);
    }



    @Override
    protected void onResume() {
        super.onResume();
        //初始化极光
        initJPush();

        determineFuJian();
//        determineHuiKuan();

    }




    private void requestCheckUpdate() {
        new ConsignorCheckUpdate().checkUpdate(getContext(), null);
    }

    private void registerWeChat() {
        IWXAPI api = WXAPIFactory.createWXAPI(this, PlatformConfig.WE_CHAT_APP_ID, false);
        api.registerApp(PlatformConfig.WE_CHAT_APP_ID);
    }

    private void requestMessageQuality(boolean isDialog) {
        mMessageModel.messageQualityModel(this, isDialog, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<List<MessageQualityInfo>>>() {
            @Override
            public void onNext(CommonResponse<List<MessageQualityInfo>> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    //消息红点是否显示
                    List<MessageQualityInfo> list = commonResponse.getData();
                    if (list != null && list.size() > 0) {
                        mTabLayout.showDot(2);
                        mTabLayout.setMsgMargin(2,30,0);

                    } else {
                        mTabLayout.hideMsg(2);
                    }
                } else {
                    LogUtil.print(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {

                LogUtil.print(e.message);
            }
        });
    }

    private void initListener() {

        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                HotUpdateController.getInstance().checkUpgrade();
                switch (position) {
                    case 0:
                        getToolbarStatus().setTitle("一键发货");
//                        getToolbarStatus().setTitle("首页");
                        getToolbarStatus().isShowToolbar(false);
                        break;
                    case 1:
                        getToolbarStatus().setTitle("运单管理");
                        getToolbarStatus().isShowToolbar(false);
                        break;
                    case 2:
                        getToolbarStatus().setTitle("消息中心");
                        getToolbarStatus().isShowToolbar(true);

                        break;
                    case 3:
                        getToolbarStatus().setTitle("个人中心");
                        getToolbarStatus().isShowToolbar(false);

                        break;
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }

    private List<CommonFragment> createFragmentList() {
        mFragmentList.add(new HomeFragment());
        mFragmentList.add(new WaybillFragment());
        mFragmentList.add(new MessageFragment());
        mFragmentList.add(new MineFragment());
        return mFragmentList;
    }

//    private List<CommonFragment> createFragmentListTwo() {
//        mFragmentList.add(new HomeFragment());
//        mFragmentList.add(new WaybillFragmentTwo());
//        mFragmentList.add(new MessageFragment());
//        mFragmentList.add(new MineFragment());
//        return mFragmentList;
//    }


    @Override
    public CommonFragment createFragment() {
        return null;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        int action = intent.getIntExtra(AppStatusConstant.KEY_HOME_ACTION, AppStatusConstant.ACTION_BACK_TO_HOME);
        switch (action) {
            case AppStatusConstant.ACTION_RESTART_APP:
                restartApp();
                break;
        }
    }

    protected void restartApp() {
        openActivity(SplashActivity.class);
        finish();
    }

    private long exitTime = 0;

    @Override
    public void onBackPressed() {

        if (System.currentTimeMillis() - exitTime > 2000) {
            exitTime = System.currentTimeMillis();
            showToast("再按一次退出程序");
            return;
        }
        finish();
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_MESSAGE_POINT:
                String message = event.getMessage();
                if (!TextUtils.isEmpty(message)) {
                    mTabLayout.showDot(1);
                } else {
                    mTabLayout.hideMsg(1);
                }
                break;
            case EVENT_REFRESH_CONSIGNOR_INFO:
                requestMessageQuality(false);
                break;
            case EVENT_MOVE_TO_MINE:
                mTabLayout.setCurrentTab(3);
                break;
            case EVENT_MOVE_TO_JISUAN:
                mTabLayout.setCurrentTab(1);
                break;
            case EVENT_MOVE_TO_YUNDAN:
                mTabLayout.setCurrentTab(1);
                break;
//            case CHANGE_TAB_FRAGMENT:
//                changeTabFragment();
//                break;


        }
    }

//    private int oldRolePosition=0;
//    private void changeTabFragment() {
//       int rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
//       if (oldRolePosition!=rolePosition) {
//           oldRolePosition=rolePosition;
//           mFragmentList.clear();
//           if (2 == rolePosition) {
//               //2 销售，3物流
//               createFragmentList();
//
//           } else {
////               createFragmentList();
//               createFragmentListTwo();
//           }
//           mPagerAdapter.refresh(mFragmentList);
//       }
//    }


    private void getShengShi(boolean isDialog) {
        mMessageModel.getShengShi(this, isDialog, this.bindLifecycle(), new ObserverResponseListener<String>() {
            @Override
            public void onNext(String commonResponse) {

                String s1=commonResponse;
                String s2=commonResponse;
//                if (commonResponse.getCode() == 20000) {
//                    Object data = commonResponse.getData();
//                    String json1=String.valueOf(data);
//                    try {
//                        JSONObject object=new JSONObject(json1);
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//
//                    String s2 = commonResponse.toString();
//                } else {
////                    LogUtil.print(commonResponse.getMsg());
//                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {

                LogUtil.print(e.message);
            }
        });
    }




    private void requestUserInfo() {

        mUserInfoModel.userInfoModel(getContext(), false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<UserInfo>>() {

            @Override
            public void onNext(CommonResponse<UserInfo> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    UserInfo userInfo = commonResponse.getData();
                    if (userInfo != null && userInfo.profile != null) {
                        RoleController.getInstance().setRole(userInfo.profile);
//                        String userId =userInfo.profile.phone;
                        long timecurrentTimeMillis = System.currentTimeMillis();
                        mqtt_id=userInfo.profile.phone+userInfo.profile.id+timecurrentTimeMillis;

                        int rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
                        if (2== rolePosition){
                            //2 销售
                            mqtt_sub_topic=mqtt_sub_topic+ApiModel.ZHU_TI_TWO;
                        }else {
                            //3物流
                            mqtt_sub_topic=mqtt_sub_topic+userInfo.profile.phone;
                        }

                        inintView();
                    }
                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }




    //mqtt
//    private Button btn_send_data;
//    private TextView tv_msg;
    //访问的地址，这里填写mqtt代理服务器ip
    private String host = ApiModel.host;
    //登录账号
    private String userName = ApiModel.userName;
    //登录密码
    private String passWord = ApiModel.passWord;
    //这个是mqtt_id  唯一id，每个客户端应该生成不同的唯一id，这里测试演示数据，我就写固定的id，打包到不同的手机上安装，要手动修改或修改成动态id，获取随机数+时间方式生成一个随机数作为唯一id
    private String mqtt_id="666";

    private int i = 1;

    private Handler handler;

    private MqttClient client;

    private String mqtt_sub_topic = ApiModel.mqtt_sub_topic; //订阅主题(消息接收方)

    private String mqtt_pub_topic ="first";//发布主题（消息发送方）

    private MqttConnectOptions options;

    private ScheduledExecutorService scheduler;


    private void inintView() {


//        btn_send_data=findViewById(R.id.btn_send_data);
//        tv_msg=findViewById(R.id.tv_msg);
//        btn_send_data.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //发送数据
//                publishmessageplus(mqtt_pub_topic,"我要发布订阅，发送数据");
//            }
//        });
        initMqtt();
        startReconnect();
        handler = new Handler() {

            @SuppressLint("SetTextIl8n")

            public void handleMessage(Message msg) {

                super.handleMessage(msg);

                switch (msg.what) {

                    case 1: //开机校验更新回传

                        break;

                    case 2: //反馈回转

                        break;

                    case 3: //MQTT收到消息回传,接收的消息
//                        tv_msg.setText(msg.obj.toString());
                        handleMqtt(msg.obj.toString());
//                        Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
                        break;

                    case 30: //连接失败

//                        Toast.makeText(MainActivity.this,"连接失败",Toast.LENGTH_SHORT).show();

                        break;

                    case 31: //连接成功

//                        Toast.makeText(MainActivity.this,"连接成功",Toast.LENGTH_SHORT).show();

                        try {

                            client.subscribe(mqtt_sub_topic,2);

                        } catch (MqttException e) {

                            e.printStackTrace();

                        }

//                        publishmessageplus(mqtt_pub_topic,"第一个客户端发送的信息");



                        break;

                    default:

                        break;

                }

            }

        };

    }

    /**
     * 初始化MQTT配制
     */
    private void initMqtt() {

        try {

            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存

            client = new MqttClient(host, mqtt_id,

                    new MemoryPersistence());

            //MQTT的连接设置

            options = new MqttConnectOptions();

            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接

            options.setCleanSession(true);

            //设置连接的用户名

            options.setUserName(userName);

            //设置连接的密码

            options.setPassword(passWord.toCharArray());

            // 设置超时时间 单位为秒

            options.setConnectionTimeout(10);

            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制

            options.setKeepAliveInterval(20);

            //设置回调

            client.setCallback(new MqttCallback() {

                @Override

                public void connectionLost(Throwable cause) {

                    //连接丢失后，一般在这里面进行重连

                    System.out.println("connectionLost----------");
                    try {
                        client.reconnect();

                    } catch (MqttException e) {
                        e.printStackTrace();
                    }catch (Exception e){
                        LogUtil.print(e.toString());
                    }

                }

                @Override

                public void deliveryComplete(IMqttDeliveryToken token) {

                    //publish后会执行到这里

                    System.out.println("deliveryComplete---------"

                            + token.isComplete());

                }

                @Override

                public void messageArrived(String topicName, MqttMessage message)

                        throws Exception {

                    //subscribe后得到的消息会执行到这里面

                    System.out.println("messageArrived----------");

                    Message msg = new Message();

                    msg.what = 3;
                    //重新编码，解决乱码问题
//                    String strMsg= new String(message.getPayload(),"GB2312");
//                    msg.obj = topicName + "---" + strMsg;
                    msg.obj =message;

                    handler.sendMessage(msg);

                }

            });

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    /**
     * 连接
     */
    private void Mqtt_connect() {

        new Thread(new Runnable() {

            @Override

            public void run() {

                try {

                    if (!(client.isConnected())){

                        client.connect(options);

                        Message msg = new Message();

                        msg.what=31;

                        handler.sendMessage(msg);

                    }



                } catch (Exception e) {

                    e.printStackTrace();

                    Message msg = new Message();

                    msg.what = 30;

                    handler.sendMessage(msg);

                }

            }

        }).start();

    }

    /**
     * 线程池执行任务，心跳包，当断开连接后，执行自动连接代理服务器
     */
    private void startReconnect() {

        scheduler = Executors.newSingleThreadScheduledExecutor();

        scheduler.scheduleAtFixedRate(new Runnable() {

            @Override

            public void run() {
                if (!client.isConnected()) {
                    Mqtt_connect();

                }

            }

        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);

    }

    /**
     * 发布订阅
     * @param topic
     * @param message2
     */
    private void publishmessageplus(String topic,String message2)

    {

        if (client == null || !client.isConnected()) {

            return;

        }

        MqttMessage message = new MqttMessage();
        message.setPayload(message2.getBytes());

        try {

            client.publish(topic,message);

        } catch (MqttException e) {



            e.printStackTrace();

        }

    }


    private void handleMqtt(String msg){
        try {
            if (!TextUtils.isEmpty(msg)){
                Gson gson=new Gson();
                int rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
                if (2== rolePosition){
                    //2 销售，3物流
                    XiaoShouHttpBean shouHttpBean = gson.fromJson(msg, XiaoShouHttpBean.class);
                    showLogTwo(shouHttpBean);
                }else {
                    HandleMqttBean mqttBean = gson.fromJson(msg, HandleMqttBean.class);
                    showLog(mqttBean);
                }

            }
        }catch (Exception e){
            LogUtil.print(e.toString());
        }

    }


    private String msg="";
    private MaterialDialog mqttDialogTwo;
    private void showLogTwo(XiaoShouHttpBean mqttBean) {
        if (null!=mqttDialogTwo) {
            if (mqttDialogTwo.isShowing() && msg.length() < 100) {
                mqttDialogTwo.dismiss();
                msg = msg + "\n" + mqttBean.getName() + "  更新了报价\n" + mqttBean.getTime();
            } else {
                mqttDialogTwo.dismiss();
                msg = mqttBean.getName() + "  更新了报价\n" + mqttBean.getTime();
            }
        }else {
            msg = mqttBean.getName() + "  更新了报价\n" + mqttBean.getTime();
        }
//        String msg=mqttBean.getName()+"  更新了报价\n"+mqttBean.getTime();
//        if (null!=mqttDialogTwo) {
//            mqttDialogTwo.dismiss();
//        }


        mqttDialogTwo = new MaterialDialog.Builder(getContext())
                .content(msg)
                .title("有新的报价")
                .positiveText("去查看")
                .negativeText("关闭")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        openActivity(BaoJiaWebActivity.class);//确认
                        msg="";
//                        EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_REFRESH_BAOJIA_LIST.getValue()));
                        Bundle bundle=new Bundle();
                        bundle.putInt("lookType",2);
                        openActivity(OnlyLookQuotListTwoActivity.class,bundle);
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        //取消
                        msg="";

                    }
                })
                .show();
//        EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_REFRESH_ORDER_LIST.getValue()));

    }


    private MaterialDialog mqttDialog;
    private void showLog(HandleMqttBean mqttBean) {

        String msg=mqttBean.getHq()+"\n销货单号："+mqttBean.getCode()+",\n从"+mqttBean.getDelivercity()+
                "到"+mqttBean.getDestinationcity()+"，"+mqttBean.getQuantity()+"吨";
        if (null!=mqttDialog) {
            mqttDialog.dismiss();
        }
//        mqttDialog = new MaterialDialog.Builder(getContext())
//                .content(msg)
//                .title("您有新的找车单")
//                .positiveText("忽略")
//                .negativeText("处理")
//                .onNegative(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        String id = mqttBean.getId();
//                        if (TextUtils.isEmpty(id)){
//                            ToastUtil.showShortToast("找车单编号出错");
//                        }else {
//                            getZhaoCheInfo(id);
//                        }
//
//                    }
//                })
//                .show();

        mqttDialog = new MaterialDialog.Builder(getContext())
                .content(msg)
                .title("您有新的找车单")
                .positiveText("确认")
                .negativeText("")
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                    }
                })
                .show();
        EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_REFRESH_ORDER_LIST.getValue()));

    }

    private void getZhaoCheInfo(String id) {
        Map<String, String> map = new HashMap<>();
        map.put("id", id);
        mUserInfoModel.getZhaoCheInfo(getContext(), map, false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<GoodsInfo>>() {
            @Override
            public void onNext(CommonResponse<GoodsInfo> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    GoodsInfo goodsInfo = commonResponse.getData();
                    if (goodsInfo != null ) {
                        Gson gson=new Gson();
                        String json = gson.toJson(goodsInfo);
                        Bundle bundle=new Bundle();
                        bundle.putString("toexamine",json);
                        openActivity(FindCarOnlyLookActivity.class, bundle);
                    }

                } else {
                    LogUtil.print(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                LogUtil.print(e.message);
            }
        });
    }



    private void initJPush() {
        JPushInterface.setDebugMode(false);    // 设置开启日志,发布时请关闭日志BuildConfig.DEBUG
        JPushInterface.init(getApplicationContext());            // 初始化 JPush
        String phone = SharedPreferenceManager.getInstance().getPhone();
        JPushInterface.checkTagBindState(this, 0, phone);
        setJPushAlia(phone);

    }

    private void setJPushAlia(String phone) {
        JPushInterface.setAlias(this, 1, phone);
    }



        // 检查通知权限状态
        private void getNotification(){
        try {

                    if (!NotificationsUtils.isNotifyEnabled(this)){
                        new PermissionDialog(this, new OnDialogClickListener() {
                            @Override
                            public void onPositiveClick() {
                                        try {

                                            Intent intent = new Intent();
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                                                intent.putExtra("android.provider.extra.APP_PACKAGE", MainActivity.this.getPackageName());
                                            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.0
                                                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                                                intent.putExtra("app_package", MainActivity.this.getPackageName());
                                                intent.putExtra("app_uid", MainActivity.this.getApplicationInfo().uid);
                                                startActivity(intent);
                                            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { //4.4
                                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                                intent.addCategory(Intent.CATEGORY_DEFAULT);
                                                intent.setData(Uri.parse("package:" + MainActivity.this.getPackageName()));
                                            } else if (Build.VERSION.SDK_INT >= 15) {
                                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                                intent.setData(Uri.fromParts("package", MainActivity.this.getPackageName(), null));
                                            }
                                            startActivity(intent);
                                        }catch (Exception e){
                                            Log.e("fei",e.toString());
                                        }
                            }

                            @Override
                            public void onNegativeClick(boolean isForce) {
//                                Toast.makeText(MainActivity.this, "拒绝", Toast.LENGTH_SHORT).show();
                            }
                        })
                                .setContent("检测到通知权限未开启!\n如果不开启权限会收不到推送通知哦~")
                                .show();
//                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this)
//                                .setCancelable(true)
//                                .setTitle("检测到通知权限未开启!")
//                                .setMessage("如果不开启权限会收不到推送通知哦~")
//                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.cancel();
//                                }
//                            })
//                                .setPositiveButton("去开启", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        try {
//                                            dialog.cancel();
//                                            Intent intent = new Intent();
//                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                                                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
//                                                intent.putExtra("android.provider.extra.APP_PACKAGE", MainActivity.this.getPackageName());
//                                            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.0
//                                                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
//                                                intent.putExtra("app_package", MainActivity.this.getPackageName());
//                                                intent.putExtra("app_uid", MainActivity.this.getApplicationInfo().uid);
//                                                startActivity(intent);
//                                            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { //4.4
//                                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//                                                intent.addCategory(Intent.CATEGORY_DEFAULT);
//                                                intent.setData(Uri.parse("package:" + MainActivity.this.getPackageName()));
//                                            } else if (Build.VERSION.SDK_INT >= 15) {
//                                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                                                intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
//                                                intent.setData(Uri.fromParts("package", MainActivity.this.getPackageName(), null));
//                                            }
//                                            startActivity(intent);
//                                        }catch (Exception e){
//                                            Log.e("fei",e.toString());
//                                        }
//                                    }
//                                });
//                        builder.create().show();
                    }
                }catch (Exception e){
                    Log.e("fei",e.toString());
                }
            }



//        private void initTuiSong() {
//            NotificationsUtils.isNotifyEnabled(this);
//        }


    //查找是否有附件合同没有上传
    private void determineFuJian() {
        try {
            String tongZhiFirst = SharedPreferenceManager.getInstance().getShiJianFirst();
            String nowTime = DateUtil.getTime();
            if (TextUtils.isEmpty(tongZhiFirst)){
                SharedPreferenceManager.getInstance().setShiJianFirst(nowTime);
                searchFuJian();
            }else {
                Long integer = Long.valueOf(tongZhiFirst);
                int chaHors = DateUtil.isChaHors(integer);
                if (chaHors>3){
                    SharedPreferenceManager.getInstance().setShiJianFirst(nowTime);
                    searchFuJian();
                }

            }
        }catch (Exception e){
            SharedPreferenceManager.getInstance().setShiJianFirst("");
            LogUtil.print(e.toString());
            searchFuJian();
        }


    }

    private void searchFuJian() {
        if (null==driverModel){
            driverModel=new DriverModel();
        }
        String consignorName = SharedPreferenceManager.getInstance().getConsignorName();
        String qianTian = Util.getQianTian();
        String qianNian = Util.getQianNian();
        Map<String, String> map = new HashMap<>();
        map.put("page", "1");
        map.put("limit", "4");
        map.put("order", "desc");
        map.put("associate", "0");
//        map.put("personname", "周月");//名字周月 孙占城
        map.put("personname", consignorName);//名字
        map.put("startDate", qianNian);
        map.put("endDate", qianTian);
        map.put("reason", "0");//0未填写原因 其他，填写了

        driverModel.getUnFuJianList(this, map, false, bindLifecycle(), new ObserverResponseListener<CommonResponse<FuJianListBean>>() {
            @Override
            public void onNext(CommonResponse<FuJianListBean> commonResponse) {
                if (!isFinishing() && !isDestroyed()) {
                    if (commonResponse.getCode() == 20000) {
                        try {
                            List<FuJianListBean.RecordsDTO> list = commonResponse.getData().getRecords();
//                        List<QuotationListBean.QuotationRecords> resultList = new ArrayList<>();

                            if (list != null && list.size() > 0) {
                                String fuJianmsg="";
                                int m=4;
                                if (list.size()<4){
                                    m=list.size();
                                }
                                for (int i=0;i<m;i++){
                                    FuJianListBean.RecordsDTO recordsDTO = list.get(i);
                                    fuJianmsg=fuJianmsg+"订单号："+recordsDTO.getCode()+"\n";
                                }
                                fuJianmsg=fuJianmsg+"......";
                                showFuJianLog(fuJianmsg);
                            }
                        }catch (Exception e){
                            LogUtil.print(e.toString());
                        }

                    } else {
                        showToast(commonResponse.getMsg());
                    }
                }
            }


            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }


    private MaterialDialog fuJianDialog;
    private void showFuJianLog(String fuJianmsg) {

//        String msg=mqttBean.getHq()+"\n销货单号："+mqttBean.getCode()+",\n从"+mqttBean.getDelivercity()+
//                "到"+mqttBean.getDestinationcity()+"，"+mqttBean.getQuantity()+"吨";
        if (null!=fuJianDialog) {
            fuJianDialog.dismiss();
        }
        fuJianDialog = new MaterialDialog.Builder(getContext())
                .content(fuJianmsg)
                .title("您有销售订单未上传附件合同")
                .negativeText("关闭")
                .positiveText("查看")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        openActivity(FuJianListActivity.class);
                    }
                })
                .show();


    }




    //查找是否回款
    private void determineHuiKuan() {

//        searchHuiKuan();

        try {
            String tongZhiFirst = SharedPreferenceManager.getInstance().getShiJianFirstHuiKuan();
            String nowTime = DateUtil.getTime();
            if (TextUtils.isEmpty(tongZhiFirst)){
                SharedPreferenceManager.getInstance().setShiJianFirstHuiKuan(nowTime);
                searchHuiKuan();
            }else {
                Long integer = Long.valueOf(tongZhiFirst);
                int chaHors = DateUtil.isChaHors(integer);
                if (chaHors>1){
                    SharedPreferenceManager.getInstance().setShiJianFirstHuiKuan(nowTime);
                    searchHuiKuan();
                }

            }
        }catch (Exception e){
            SharedPreferenceManager.getInstance().setShiJianFirstHuiKuan("");
            LogUtil.print(e.toString());
            searchHuiKuan();
        }


    }

    private void searchHuiKuan() {
        if (null==driverModel){
            driverModel=new DriverModel();
        }
        Map<String, String> map = new HashMap<>();
        map.put("page", "1");
        map.put("limit", "4");
        map.put("isAudit", "0");

        driverModel.getUnHuiKuanList(this, map, false, bindLifecycle(), new ObserverResponseListener<CommonResponse<HuiKuanListBean>>() {
            @Override
            public void onNext(CommonResponse<HuiKuanListBean> commonResponse) {
                if (!isFinishing() && !isDestroyed()) {
                    if (commonResponse.getCode() == 20000) {
                        try {
                            List<HuiKuanListBean.RecordsDTO> list = commonResponse.getData().getRecords();
//                        List<QuotationListBean.QuotationRecords> resultList = new ArrayList<>();

                            if (list != null && list.size() > 0) {
                                String fuJianmsg="";
                                int m=4;
                                if (list.size()<4){
                                    m=list.size();
                                }
                                for (int i=0;i<m;i++){
                                    HuiKuanListBean.RecordsDTO recordsDTO = list.get(i);
                                    fuJianmsg=fuJianmsg+"销货单号："+recordsDTO.getSaleDeliveryCode()+"\n";
                                }
                                fuJianmsg=fuJianmsg+"......";
                                showHuiKuanLog(fuJianmsg);
                            }
                        }catch (Exception e){
                            LogUtil.print(e.toString());
                        }

                    } else {
                        showToast(commonResponse.getMsg());
                    }
                }
            }


            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }


    private MaterialDialog huikuanDialog;
    private void showHuiKuanLog(String fuJianmsg) {

//        String msg=mqttBean.getHq()+"\n销货单号："+mqttBean.getCode()+",\n从"+mqttBean.getDelivercity()+
//                "到"+mqttBean.getDestinationcity()+"，"+mqttBean.getQuantity()+"吨";
        if (null!=huikuanDialog) {
            huikuanDialog.dismiss();
        }
        huikuanDialog = new MaterialDialog.Builder(getContext())
                .content(fuJianmsg)
                .title("您有销售订单未回款")
                .negativeText("关闭")
                .positiveText("查看")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        openActivity(UnHuiKuanListActivity.class);
                    }
                })
                .show();


    }

















}
